<template>
	<el-dialog :title="'批量绑定安装点'" v-model="visible" destroy-on-close :close-on-click-modal="false" draggable width="880px">
		<el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="130px" v-loading="loading">
			<el-row :gutter="24">
				<el-col :span="20" class="mb20">
					<el-form-item label="单位" prop="deptId">
						<el-tree-select
							v-model="form.deptId"
							:data="parentData"
							:props="{ value: 'id', label: 'name', children: 'children', disabled: 'isLock' }"
							clearable
							filterable
							check-strictly
							default-expand-all
							:render-after-expand="false"
							placeholder="请选择授权单位"
							ref="treeRef"
							@change="handleDeptChange"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="建筑物" prop="buildingId">
						<el-select v-model="form.buildingId" filterable placeholder="请选择" @change="handleBuildChange">
							<el-option v-for="item in buildingOptions" :key="item.id" :label="item.buildingName" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle @click="BuildingDialogRef.openDialog()"></el-button>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="楼层" prop="floorId">
						<el-select v-model="form.floorId" filterable placeholder="请选择" :disabled="!form.buildingId">
							<el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle :disabled="!form.buildingId" @click="FloorDialogRef.openDialog()"></el-button>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="接警联系人" prop="alarmWorkerId">
						<el-select v-model="form.alarmWorkerId" filterable placeholder="请选择" :disabled="!form.deptId">
							<el-option v-for="item in contactOptions" :key="item.id" :label="item.name" :value="item.id" />
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="4">
					<el-button icon="Plus" class="ml-4" type="primary" circle :disabled="!form.deptId" @click="ContactDialogRef.openDialog()"></el-button>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="地图标记" prop="longitude">
						<el-button type="primary" icon="location" @click="AMapDialogRef.openDialog(form)">精确选择</el-button>
						<span class="ml-1">{{ form.longitude }}</span>
						<span class="ml-2">{{ form.latitude }}</span>
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="详细地址" prop="detailAddress">
						<el-input v-model="form.detailAddress" placeholder="请输入详细地址" maxlength="250" />
					</el-form-item>
				</el-col>
				<el-col :span="20" class="mb20">
					<el-form-item label="安装点名称" prop="address">
						<el-input v-model="form.address" placeholder="请输入安装点名称" maxlength="200" />
					</el-form-item>
				</el-col>

				<el-col :span="20" class="mb20">
					<el-form-item label="安装点备注" prop="remarks">
						<el-input autosize type="textarea" v-model="form.remarks" placeholder="请输入内容" maxlength="500" />
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
		</template>
	</el-dialog>
	<!-- 地图精确选择 -->
	<AMapDialog ref="AMapDialogRef" @confirm="handleAMapConfirm" />
	<!-- 新增建筑物 -->
	<BuildingDialog ref="BuildingDialogRef" @refresh="getBuidingAndContactAll(form.deptId)" />
	<!-- 新增楼层 -->
	<FloorDialog ref="FloorDialogRef" @refresh="getFloorByBuilding(form.buildingId)" />
	<!-- 新增接警人 -->
	<ContactDialog ref="ContactDialogRef" @refresh="getBuidingAndContactAll(form.deptId)" />
</template>

<script setup lang="ts" name="BatchInstall">
import { useMessage, useMessageBox } from '/@/hooks/message';
import { saveBatch } from '/@/api/installation/basicInstallLocation';
import { fetchListAll as fetchBuildingListAll, getObj as getBuidingObj } from '/@/api/installation/basicPlaceBuilding';
import { fetchListAll as fetchFloorListAll } from '/@/api/installation/basicPlaceFloor';
import { fetchListAll as fecthContactListAll } from '/@/api/installation/basicAlarmContacts';
import { deptTree } from '/@/api/admin/dept';
import { useUserInfo } from '/@/stores/userInfo';
const userStores = useUserInfo();
const { userInfos } = storeToRefs(userStores);
const AMapDialog = defineAsyncComponent(() => import('/@/views/installation/basicPlaceBuilding/components/AMap.vue'));
const BuildingDialog = defineAsyncComponent(() => import('/@/views/installation/basicPlaceBuilding/form.vue'));
const FloorDialog = defineAsyncComponent(() => import('/@/views/installation/basicPlaceFloor/form.vue'));
const ContactDialog = defineAsyncComponent(() => import('/@/views/installation/basicAlarmContacts/form.vue'));
const emit = defineEmits(['refresh']);
const BuildingDialogRef = ref();
const FloorDialogRef = ref();
const ContactDialogRef = ref();
// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const buildingOptions = ref<any[]>([]);
const floorOptions = ref<any[]>([]);
const contactOptions = ref<any[]>([]);
const parentData = ref([]);
const AMapDialogRef = ref();
const deviceList: any = ref([]);
// 定义字典

// 提交表单数据
const form = reactive({
	id: '',
	address: '',
	buildingId: '',
	buildingName: '',
	floorId: '',
	alarmWorkerId: '',
	longitude: '',
	latitude: '',
	detailAddress: '',
	remarks: '',
	deviceId: null,
	deptId: '',
	deviceType: '',
	deviceModelName: '',
	imei: '',
});

// 定义校验规则
const dataRules = ref({
	deptId: [{ required: true, message: '请选择单位', trigger: 'change' }],
	address: [{ required: true, message: '安装点名称不能为空', trigger: 'blur' }],
	alarmWorkerId: [{ required: true, message: '接警人员不能为空', trigger: 'change' }],
	longitude: [{ required: true, message: '请选择地图标记', trigger: 'blur' }],
	detailAddress: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
});

// 打开弹窗
const openDialog = (rows: any) => {
	deviceList.value = rows;
	visible.value = true;
	// 重置表单数据
	nextTick(() => {
		dataFormRef.value?.resetFields();
		form.deptId = userInfos.value.user.deptId;
	});
	getDeptData();
	// 获取basicInstallLocation信息
	handleDeptChange(userInfos.value.user.deptId);
};

// 提交
const onSubmit = async () => {
	const valid = await dataFormRef.value.validate().catch(() => {});
	if (!valid) return false;
	const hasDiffDept = deviceList.value.findIndex((d: { deptId: string }) => d.deptId !== form.deptId);
	if (hasDiffDept !== -1) {
		try {
			await useMessageBox().confirm('是否把设备过户给这个单位？');
		} catch (e) {
			return;
		}
	}
	try {
		loading.value = true;
		const params = Object.assign({}, form, { deviceIds: deviceList.value.map((d: { id: string }) => d.id) });
		await saveBatch(params);
		useMessage().success('操作成功');
		visible.value = false;
		emit('refresh');
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

const getDeptData = async () => {
	deptTree().then((res) => {
		parentData.value = res.data;
	});
};
const handleAMapConfirm = (data: any) => {
	const { lat, lng, address, building } = data;
	form.latitude = lat;
	form.longitude = lng;
	form.detailAddress = address;
	form.address = building;
};
// 选择单位-查询建筑物,接警人
const handleDeptChange = (id: string) => {
	form.buildingId = '';
	form.alarmWorkerId = '';
	form.floorId = '';
	getBuidingAndContactAll(id);
};
const getBuidingAndContactAll = (id: string) => {
	fetchBuildingListAll({ deptId: id }).then((res) => {
		buildingOptions.value = res.data;
	});
	fecthContactListAll({ deptId: id }).then((res) => {
		contactOptions.value = res.data;
	});
};
// 选择建筑物-查询楼层
const handleBuildChange = (id: string) => {
	form.floorId = '';
	getFloorByBuilding(id);
	getBuidingObj(id).then((res) => {
		form.latitude = res.data.latitude;
		form.longitude = res.data.longitude;
		form.detailAddress = res.data.detailAddress;
		form.address = res.data.buildingName;
	});
};
// 查询楼层
const getFloorByBuilding = (id: string) => {
	fetchFloorListAll({ buildingId: id }).then((res) => {
		floorOptions.value = res.data;
	});
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>
